package root;

import game.BasicGrid;
import game.Grid;

import java.util.ArrayList;
import java.util.List;
import java.util.Random;


//une pour les dominer toutes
public class GridOfWords extends BasicGrid{
	
	private List<Word> mWords = new ArrayList<Word>();
	
	public GridOfWords(char[][] state) {
		super(state);
		setWords();
	}
	
	public GridOfWords(int nbRow, int nbCol) {
		super(nbRow,nbCol);
		setBlackCase();
		setWords();
	}
	
	public GridOfWords()
	{}
	
	@Override
	public Grid clone()
	{
		GridOfWords g = new GridOfWords();
		g.rowsCount = rowsCount;
		g.colsCount = colsCount;
		g.setWords(mWords);
		g.gridState = toState();
		
		return g;
	}
	
	private final void setBlackCase()
	{
		Random rdm = new Random();
		int nbBlackCase = colsCount * rowsCount*18/100;
		System.out.println("nombre de black case = "+nbBlackCase);
		
		for(int i=0; i<nbBlackCase; i++)
		{
			int column = rdm.nextInt(colsCount);
			int line = rdm.nextInt(rowsCount);
			gridState[line][column] = BLACK;
		}
		
		System.out.println(this);
		
	}
	
	private final void setWords()
	{
		String word;
		for(int i=0; i<rowsCount;i++)
		{
			for(int j=0; j<colsCount; j++)
			{
				word = getWord(i, j, Direction.HORIZONTAL);
				if(word!=null)
				{
					mWords.add(new Word(this,i,j,Direction.HORIZONTAL));
					j+=word.length();
				}
			}
		}
		
		for(int j=0; j<colsCount;j++)
		{
			for(int i=0; i<rowsCount; i++)
			{
				word = getWord(i, j, Direction.VERTICAL);
				if(word!=null)
				{
					mWords.add(new Word(this,i,j,Direction.VERTICAL));
					i+=word.length();
				}
			}
		}
	}
	
	public void setWords(List<Word> words)
	{
		mWords = words;
	}
	
	@Override
	public final GridOfWords write(int row, int col, String word, Direction direction) {
		GridOfWords g = (GridOfWords) super.write(row, col, word, direction);
		g.setWords(mWords);
		
		for(Word w : mWords)
			w.onLettersChanged(g);
				
		return g;
	}
	
	public GridOfWords write(Word w, String word)
	{
		return write(w.getRow(),w.getColumn(), word, w.getDirection());
	}

	public Word getCurrentWord() {
		Word current = null;
		int nbConstraint = -1;
		
		for(Word w : mWords) 
		{
			if(!w.isFull() && nbConstraint < w.getNbConstraint())
				current = w;
		}
				
		return current;
	}
	
	public List<Word> getWords()
	{
		return mWords;
	}
	
}
